import {Component, OnInit, ViewChild} from '@angular/core';
import {tuikeSystemUrl} from "../../../../config/api";
import {HttpService} from "../../../lib/service/http.service";
import {AccountService} from "../../../lib/service/tuike/account.service";
import {RoleService} from "../../../lib/service/tuike/role.service";
import {ModalDirective} from "ngx-bootstrap";

export class AddUser {
  user_name: string;
  password: string;
  role_ids: any;

  constructor() {
    this.user_name = '';
    this.password = '';
  }
}

//
export class EditUser {
  user_name: string;
  password: string;
  role_ids: any;
  id: any;

  constructor() {
    this.user_name = '';
    this.password = '';
  }
}

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss'],
  providers: [AccountService, RoleService]
})
export class AccountComponent implements OnInit {
  addUser = new AddUser();
  editUser = new EditUser();
  staticModal;
  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 12;
  _isSpinning = false;
  accoutList = [];
  roleList = [];
  fileList = [];
  picList = [];
  checkRoles = [];
  type: string;
  message: string;
  isShow: boolean = false;
  editId = null;
  admin_status: boolean = true;
  edit_admin_role: any;
  delId = null;
  savedPassword: string;
  changed: boolean = false;
  passwordError = false;
  passwordError1 = false;
  accountError = false;
  accountError1 = false;


  @ViewChild('editAccountModal') public editAccountModal: ModalDirective;
  @ViewChild('accountModal') public accountModal: ModalDirective;
  @ViewChild('deleteModal') public deleteModal: ModalDirective;


  constructor(private httpService: HttpService, private accountService: AccountService, private roleService: RoleService) {
  }

  ngOnInit() {
    this.getAccountList();
    this.getRoleList();
  }

  pageChanged(event: any): void {

  }

  checkedRoleIds(e) {
    console.log(e);
  }

  _console(e) {
    console.log(e);
  }


  showAddModal() {
    this.addUser = new AddUser();
    this.editId = null;
    this.checkRoles.map((e, i) => {
      e['checked'] = false;
    })
    this.accountModal.show();
  }

  showDelAccountModal(id) {
    this.delId = id;
    this.deleteModal.show();
  }

  getAccountList() {
    const url = `${tuikeSystemUrl}/api/v1/admin/rbac/admin_index?page=${this.currentPage}&pageSize=${this.itemsPerPage}`;
    this._isSpinning = true;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.accoutList = res.data.data;
        this.totalItems = res.data.total;
        this._isSpinning = false;
      }
    })
  }

  getRoleList() {
    return new Promise((resolve, reject) => {
      this.checkRoles = [];
      this.roleService.getRoleList(1, 100).subscribe(res => {
        if (res.code === 200) {
          this.roleList = res.data.data;
          this.roleList.map((e, i) => {
            this.checkRoles.push({
              label: e.role_name,
              value: e.id,
              checked: false
            });
          });
          resolve();
        }
      });

    });

  }

  _log(e) {
    console.log(e);
  }

  clearCheckedState() {
    this.checkRoles.map((e, i) => {
      e['checked'] = false;
    })
  }

  delUser() {
    this.accountService.delUser({id: this.delId}).subscribe(res => {
      if (res.code === 200) {
        this.isShow = true;
        this.message = '删除成功';
        this.type = 'success';
        this.deleteModal.hide();
        this.getAccountList();
      } else {
        this.isShow = true;
        this.message = res.message;
        this.type = 'error';
      }
    })
  }

  checkAccount(e,where) {
    if(where == 'add') {
      if (e.length < 3) {
        this.accountError = true;
      } else {
        this.accountError = false;
      }
    } else {
      if (e.length < 3) {
        this.accountError1 = true;
      } else {
        this.accountError1 = false;
      }
    }

  }

  checkLength(e) {
    if (e.length < 6) {
      this.passwordError = true;
    } else {
      this.passwordError = false;
    }
  }

  inputPassword() {
    if (this.editUser.password == this.savedPassword) {
      this.editUser.password = '';
    }
  }

  consolePassword(e) {
    this.changed = true;
    if (e.length < 6) {
      this.passwordError1 = true;
    } else {
      this.passwordError1 = false;
    }
  }

  recoveryPassword() {
    if (!this.changed) {
      this.editUser.password = this.savedPassword;
    }
  }

  cancel() {
    this.editAccountModal.hide();
    this.editUser.password = this.savedPassword;
    this.changed = false;
    this.passwordError1 = false;
    this.accountError1 = false;
  }

  getAccountInfo(id) {
    this.accountService.getAccountInfo(id).subscribe(res => {
      if (res.code === 200) {
        this.editUser.user_name = res.data.user_name;
        this.savedPassword = res.data.password;
        this.editUser.password = res.data.password;
        this.edit_admin_role = res.data.admin_to_role;
        this.getRoleList().then(() => {
          this.clearCheckedState();
          this.checkInfoState(this.edit_admin_role);
        });
        this.admin_status = res.data.admin_status;
      }
    })
  }

  checkInfoState(data) {
    this.checkRoles.map((e, i) => {
      data.map((e1, i1) => {
        if (e.value == e1.role_id) {
          e['checked'] = true;
        }
      })
    });
  }

  picChange() {

  }

  picError = false;

  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  showEditAccountModal(id) {
    this.editId = id;
    this.getAccountInfo(id);
    this.editAccountModal.show();
  }


  addUserSubmit() {
    this.addUser.role_ids = [];
    this.checkRoles.map((e, i) => {
      if (e.checked) {
        this.addUser.role_ids.push(e.value);
      }
    });
    this.addUser.role_ids = JSON.stringify(this.addUser.role_ids).substring(1, JSON.stringify(this.addUser.role_ids).length - 1);
    this.accountService.addUser(this.addUser).subscribe(res => {
      if (res.code === 200) {
        this.isShow = true;
        this.message = '添加成功';
        this.type = 'success';
        this.accountModal.hide();
        this.getAccountList();
        this.addUser = new AddUser();
        this.editId = null;
      }
    });
  }

  editUserSubmit() {
    this.editUser.role_ids = [];
    this.editUser['id'] = this.editId;
    this.editUser['admin_status'] = this.admin_status;
    if (!this.changed && this.savedPassword == this.editUser.password) {
      this.editUser['password'] = '';
    }
    this.checkRoles.map((e, i) => {
      if (e.checked) {
        this.editUser.role_ids.push(e.value);
      }
    });
    this.editUser.role_ids = JSON.stringify(this.editUser.role_ids).substring(1, JSON.stringify(this.editUser.role_ids).length - 1);
    this.accountService.editUser(this.editUser).subscribe(res => {
      if (res.code === 200) {
        this.isShow = true;
        this.message = '修改成功';
        this.type = 'success';
        this.editAccountModal.hide();
        this.getAccountList();
        this.editId = null;
      } else {
        this.isShow = true;
        this.message = '修改失败';
        this.type = 'error';
      }
    });
  }
}
